
// 预加载脚本：在渲染进程中通过安全桥暴露必要的 API
// 专注悬浮球右键拖拽相关 API

const electron = require('electron')
const { contextBridge, ipcRenderer } = electron
const desktopCapturer = electron.desktopCapturer

contextBridge.exposeInMainWorld('electronAPI', {
  // 右键拖拽：开始，传入在窗口内的鼠标偏移（用于定位）
  dragStart: (offset) => ipcRenderer.send('floatball:drag-start', offset),

  // 右键拖拽：移动，获取系统光标全局位置并传递给主进程
  dragMove: async () => {
    const globalPoint = await ipcRenderer.invoke('system:get-cursor')
    ipcRenderer.send('floatball:drag-move', globalPoint)
  },

  // 右键拖拽：结束
  dragEnd: () => ipcRenderer.send('floatball:drag-end'),

  // 系统通知：通过主进程触发原生系统通知
  notify: (options) => ipcRenderer.send('system:notify', options),
})

// 搜索相关 API：统一暴露在 electronSearchAPI
contextBridge.exposeInMainWorld('electronSearchAPI', {
  // Vue2 渲染进程调用：单参数关键字，搜索并打开最佳匹配
  searchAndOpen: (keyword) => ipcRenderer.invoke('search_open:keyword', keyword),
  // 精确：仅按文件名搜索并打开（兼容新签名）
  // 用法：
  // - searchAndOpenFile('readme.txt')
  // - searchAndOpenFile(['C:/Users/me/Desktop'], '方案一.md', { depthLimit: 4 })
  // - searchAndOpenFile({ directories: ['D:/Docs'], keyword: 'offer2.txt', options: { maxResults: 30 } })
  searchAndOpenFile: (arg1, arg2, arg3) => {
    if (Array.isArray(arg1)) {
      return ipcRenderer.invoke('search_open:file', arg1, arg2, arg3)
    }
    if (typeof arg1 === 'object' && arg1) {
      return ipcRenderer.invoke('search_open:file', arg1)
    }
    return ipcRenderer.invoke('search_open:file', arg1)
  },
  // 精确：仅按应用名搜索并打开
  searchAndOpenApp: (appname) => ipcRenderer.invoke('search_open:app', appname),
  // 状态监听：搜索/打开过程状态变化
  onStatusChange: (handler) => {
    const listener = (_, payload) => {
      try { handler && handler(payload) } catch (_) {}
    }
    ipcRenderer.on('search:status', listener)
    return () => ipcRenderer.removeListener('search:status', listener)
  },
})


// 设置相关 API：目录选择、读取/保存工作目录、更新事件
contextBridge.exposeInMainWorld('electronSettingsAPI', {
  selectDirectories: () => ipcRenderer.invoke('dialog:select-dirs'),
  getWorkDirs: () => ipcRenderer.invoke('settings:get-workdirs'),
  setWorkDirs: (dirs) => ipcRenderer.invoke('settings:set-workdirs', dirs),
  onWorkDirsUpdated: (handler) => {
    const listener = (_, payload) => {
      try { handler && handler(payload) } catch (_) {}
    }
    ipcRenderer.on('settings:workdirs-updated', listener)
    return () => ipcRenderer.removeListener('settings:workdirs-updated', listener)
  }
})

// 文件/目录操作：统一 Promise 返回 { success, ... }
contextBridge.exposeInMainWorld('electronFileAPI', {
  // 文件
  createFile: (path, content = '', options = {}) => ipcRenderer.invoke('createFile', path, content, options),
  writeFile: (path, content = '', options = {}) => ipcRenderer.invoke('writeFile', path, content, options),
  readFile: (path, options = {}) => ipcRenderer.invoke('readFile', path, options),
  deleteFile: (path) => ipcRenderer.invoke('deleteFile', path),
  renameFile: (fromPath, toPath, options = {}) => ipcRenderer.invoke('renameFile', fromPath, toPath, options),
  // 目录
  createDir: (path, options = {}) => ipcRenderer.invoke('createDir', path, options),
  deleteDir: (path, options = {}) => ipcRenderer.invoke('deleteDir', path, options),
  readDir: (path) => ipcRenderer.invoke('readDir', path),
})

// 模板管理 API（基于项目根目录/template）
contextBridge.exposeInMainWorld('electronTemplateAPI', {
  listCategories: () => ipcRenderer.invoke('template:list-categories'),
  listTemplates: (category) => ipcRenderer.invoke('template:list-templates', category),
  saveTemplate: (payload) => ipcRenderer.invoke('template:save', payload), // { category, name, data, mime }
  deleteTemplate: (category, name) => ipcRenderer.invoke('template:delete', { category, name }),
  deleteCategory: (category) => ipcRenderer.invoke('template:delete-category', category),
  getTemplateDataURL: (category, name) => ipcRenderer.invoke('template:get-dataurl', { category, name }),
  getTemplatePath: (category, name) => ipcRenderer.invoke('template:get-path', { category, name }),
})

// 暴露给渲染进程：系统模拟 API（鼠标、键盘、滚轮）
contextBridge.exposeInMainWorld('electronSimulateAPI', {
  mouse: (payload) => ipcRenderer.invoke('simulate:mouse', payload),
  keyboard: (payload) => ipcRenderer.invoke('simulate:keyboard', payload),
  scroll: (payload) => ipcRenderer.invoke('simulate:scroll', payload)
})

// 截屏
contextBridge.exposeInMainWorld('electronCaptureAPI', {
  takeScreenshot: () => ipcRenderer.invoke('take-screenshot'),
  // 可以添加其他需要的方法
});